import { i18n } from '@app-nextmesh/common/utils';
import {
  AmcaxProp,
  ARRAY_TYPES,
  ENTITY_TYPES,
  HandleChange,
  IAmcaxProp,
  JsonReservedFields,
  TYPE_BOOL,
  TYPE_DOUBLE,
  TYPE_DYNAMIC_TABLE,
  TYPE_EXPRESSION,
  TYPE_GROUP,
  TYPE_INT,
  TYPE_OPTION,
  TYPE_SET_ELEMENT,
  TYPE_SET_NODE,
  TYPE_SET_SURFACE,
  TYPE_SET_REFER_POINT,
  TYPE_TABULAR,
  VALUE_TYPE,
} from '@app-nextmesh/types';
import { splitByUppercase } from '@app-nextmesh/utils';
import { isArray, isEmpty, isPlainObject } from 'lodash';

export const isEntityTypes = (type: string[]) => {
  if (typeof type === 'string') {
    if (ENTITY_TYPES.includes(type)) {
      return true;
    }
  } else {
    if (isArray(type) && type.every((t) => ENTITY_TYPES.includes(t))) {
      return true;
    }
  }
  return false;
};

/**
 * 扁平化form
 * @param formFormat 用于渲染的表单格式
 * @returns 扁平化的from，比如： 
 * {
      "CurvatureFactor": 0.2,
      "GrowthRate": 1.3,
      "MaxSize": 1000,
      "MeshingDim": 2,
      "MinSize": 50,
      "SelectedEntities": [7,8,9,10,11,12,13,14,15,16,17,18,19]
    }
 */
export const makeDefaultForm2 = (formFormat: object) => {
  const newForm = makeDefaultForm(formFormat);
  // 扁平化form，遍历每一项
  const flatForm = {};
  const names = Object.keys(newForm);
  names.forEach((name) => {
    const item = newForm[name];
    // 跳过保留字段
    if (JsonReservedFields.includes(name)) {
      return;
    }
    // TODO 需要处理有嵌套Form的情况
    // 如果item只有Type和Value字段，则直接将Value赋值
    const type = item.Type;
    if (VALUE_TYPE.includes(type) && item.Unit == null) {
      flatForm[name] = item.Value;
    } else {
      flatForm[name] = item;
    }
  });
  return flatForm;
};

export const makeDefaultForm = (formFormat: object) => {
  /**
   * formFormat 格式示例：
   * {
      "Selection": {
          "Type": ["Volume"]
      },
      "Force": {
          "Type": "Arrayd",
          "Unit": "N",
          "Default": [0, 0, 0]
      }
    }
   */
  const newForm = {};
  if (!formFormat) {
    return newForm;
  }
  const keys = Object.keys(formFormat);
  keys.forEach((key) => {
    const item = formFormat[key];
    // 跳过保留字段
    if (JsonReservedFields.includes(key)) {
      return;
    }
    const amcaxProp = getAmcaxProp(item);
    if (amcaxProp) {
      if (amcaxProp.childCreatable) {
        newForm[key] = [];
        return;
      } else if (amcaxProp.selfEditKey !== null) {
        newForm[key] = makeDefaultForm(item);
        return;
      }
    }
    // 跳过Type,Label
    if (key === 'Type' || key === 'Label' || key === HandleChange) {
      return;
    }
    // 初始化的时候添加处理多选的表单条件。
    if (!item.Maskable && !item.HandleChange) {
      newForm[key] = makeDefaultFormItem(item);
    }
  });
  return newForm;
};

export const makeDefaultFormItem = (item) => {
  let newFormItem = {};
  if (!item) {
    return newFormItem;
  }
  const type = item.Type; // 每项首先有一个 Type 字段
  if (isEntityTypes(type)) {
    const entityType = isArray(type) ? type[0] : type;
    // 选择顶点、边、面、体
    newFormItem = { Type: entityType, Value: [] };
  } else if (ARRAY_TYPES.includes(type)) {
    // 输入多个数值类型
    let defaultUnit = item.DefaultUnit;
    if (Array.isArray(defaultUnit) && !isEmpty(defaultUnit)) {
      defaultUnit = defaultUnit[0];
    }
    const defaultValue = item.Default ?? [];
    newFormItem = {
      Type: type,
      Value: defaultValue,
    };
  } else if ([TYPE_DOUBLE, TYPE_INT, TYPE_EXPRESSION].includes(type)) {
    let defaultUnit = item.DefaultUnit;
    if (Array.isArray(defaultUnit) && !isEmpty(defaultUnit)) {
      defaultUnit = defaultUnit[0];
    }
    const defaultValue = item.Default ?? 0;
    newFormItem = { Type: type, Unit: defaultUnit, Value: defaultValue };
  } else if (type === TYPE_BOOL) {
    const defaultValue = item.Default ?? false;
    newFormItem = { Type: type, Value: defaultValue };
  } else if (type === TYPE_TABULAR) {
    newFormItem = { Type: type };
    const valueKeys = Object.keys(item);
    const value = {};
    // 遍历item的非Type字段，生成Value
    valueKeys.forEach((valueKey) => {
      // 跳过Type,Label
      if (valueKey === 'Type' || valueKey === 'Label') {
        return;
      }
      const defaultValue = item[valueKey]; // {"Unit": "mm", "Default": [0, 1]}
      let defaultUnit = defaultValue.DefaultUnit;
      if (Array.isArray(defaultUnit) && !isEmpty(defaultUnit)) {
        defaultUnit = defaultUnit[0];
      }
      value[valueKey] = {
        Unit: defaultUnit,
        Value: defaultValue.Default ?? [],
      };
    });
    newFormItem = { Type: type, Value: value };
  } else if (
    type === TYPE_SET_NODE ||
    type === TYPE_SET_ELEMENT ||
    type === TYPE_SET_SURFACE ||
    type === TYPE_SET_REFER_POINT
  ) {
    newFormItem = { Type: type, Value: [] };
  } else if (type === TYPE_OPTION) {
    newFormItem = { Type: type, Value: item.Default };
  } else if (type === TYPE_GROUP) {
    // 获取item，各字段的默认值
    newFormItem = { Type: type, Value: makeDefaultForm(item) };
  } else if (type === TYPE_DYNAMIC_TABLE) {
    newFormItem = {
      Type: type,
      Value: item.Default ?? [],
    };
  } else if (isPlainObject(type)) {
    const formType = item.Default ?? Object.keys(type)[0];
    newFormItem = {
      Type: formType,
      Value: makeDefaultForm(type[formType]),
    };
  }
  return newFormItem;
};

export const getLabel = (name: string) => {
  let label = i18n.t(name);
  if (label === name) {
    label = splitByUppercase(name);
  }
  return label;
};

const getAmcaxProp = (jsonFormFormat: any): IAmcaxProp => {
  const amcaxProp = jsonFormFormat?.[AmcaxProp];
  return amcaxProp;
};
const getSelfEditKey = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.selfEditKey;
// 是否可以添加新的项（通过右键出菜单进行添加）
const isChildCreatable = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.childCreatable;
const isOnlyOne = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.onlyOne;
const autoCreateChild = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.autoCreateChild;
/**
 * 判断是否需要显示子项
 * @param jsonFormFormat
 * @returns
 */
const notListChildren = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.notListChildren;
const clickChildShowMe = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.clickChildShowMe;
// 是否可以编辑名称
const isNameEditable = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.nameEditable !== false;
// 是否显示Type，暂时Type都不可修改
const isShowType = (jsonFormFormat: any) =>
  getAmcaxProp(jsonFormFormat)?.showType;
export {
  autoCreateChild,
  clickChildShowMe,
  getAmcaxProp,
  getSelfEditKey,
  isChildCreatable,
  isNameEditable,
  isOnlyOne,
  isShowType,
  notListChildren,
};
